package com.springboot.extend;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: TongRui乀
 * @Date: 2020-04-12 9:40
 * @description： 自定义的Mybatis 类型映射器
 */
@Slf4j
public class CustomerTypeHandler implements TypeHandler<String> {

    /**
     *  传入参数的时候 处理
     * @param preparedStatement
     * @param i
     * @param s
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
        log.info("类型处理器现在处理的字段索引为：{}， 字段值为：{}, jdbcType为：{}", i, s, jdbcType);
        try {
            String newS = new String(s.getBytes("UTF-8")) + "_typeHandler";
            log.info("处理后的字段值为：{}", newS);
            preparedStatement.setString(i, newS);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     *  根据字段名处理返回值
     * @param resultSet
     * @param s
     * @return
     * @throws SQLException
     */
    @Override
    public String getResult(ResultSet resultSet, String s) throws SQLException {
        return resultSet.getString(s).replaceAll("_typeHandler","");
    }

    /**
     *  根据索引处理返回值
     * @param resultSet
     * @param i
     * @return
     * @throws SQLException
     */
    @Override
    public String getResult(ResultSet resultSet, int i) throws SQLException {
        return resultSet.getString(i).replaceAll("_typeHandler","");
    }

    /**
     *  根据索引处理返回值
     * @param callableStatement
     * @param i
     * @return
     * @throws SQLException
     */
    @Override
    public String getResult(CallableStatement callableStatement, int i) throws SQLException {
        return callableStatement.getString(i).replaceAll("_typeHandler","");
    }
}
